const util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
const user = require('../../../utils/user.js');
var check = require('../../../utils/check.js');

const app = getApp()


// pages/ucenter/Supplier/Supplier.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    zz1:[],
    picker: ['餐饮', '果蔬', '花卉', '丽人', '母婴'],
    picker1: ['一月（280元）', '二月（280元）', '三月（520元）', '4月（1000元）', '5月（1750元）'],
    address: '',
    time: '',
    time1: '',
    index: '',
    index1: '',
    imgList: [],
    imgList1: [],
    name: '',
    shopname: '',
    phone: '',
    lat: '',
    lng: '',
    des: '',
    imag: '',
    imag1: ''
  },


  getPhoneNumber(e) {
    let that = this
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)
    util.request(api.Phone, {
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv
    }, 'get', {
        'Content-Type': 'application/json',
        'X-Qxmall-Token': wx.getStorageSync('token')
      }).then(function (res) {
        console.log(res)
        wx.setStorageSync("phone", res.data.phone.phoneNumber)
        that.setData({
          phone: res.data.phone.phoneNumber
        })
      });

  },

  PickerChange(e) {
    console.log(e);
    this.setData({
      index: e.detail.value
    })
  },
  PickerChange1(e) {
    console.log(e);
    this.setData({
      index1: e.detail.value
    })
  },

  getwz() {
    let that = this
    wx.chooseLocation({
      success: function(res) {
        console.log(res)
        that.setData({
          address: res.address,
          lat: res.latitude,
          lng: res.longitude
        })
      },
    })
  },

  TimeChange(e) {
    this.setData({
      time: e.detail.value
    })
  },
  TimeChange1(e) {
    this.setData({
      time1: e.detail.value
    })
  },


  ChooseImage() {
    let that = this
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: 'https://demo.qxshop.xyz/storage/multipleSave', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data"
          },
          formData: {
            'user': 'test'
          },
          success(res) {
            console.log(res.data)
            var bb = JSON.stringify(res.data)
            console.log(bb.data)
            var sstr = bb.split("\"");
            console.log(sstr[sstr.length - 3])
            //do something
            that.setData({
              imag: sstr[sstr.length - 3]
            })
          }
        })
        if (that.data.imgList.length != 0) {
          that.setData({
            imgList: that.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          that.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      content: '确定要删除这段回忆吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },


  ChooseImage1() {
    wx.chooseImage({
      count: 3, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        if (this.data.imgList1.length != 0) {
          this.setData({
            imgList1: this.data.imgList1.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList1: res.tempFilePaths
          })
        }

        let that = this
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          wx.uploadFile({
            url: api.MultipleSave, //仅为示例，非真实的接口地址
            filePath: res.tempFilePaths[i],
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            formData: {
              'user': 'test'
            },
            success(res) {
              console.log(res.data)
              var bb = JSON.stringify(res.data)
              console.log(bb.data)
              var sstr = bb.split("\"");
              var gg = sstr[sstr.length - 3]
              gg = gg.substring(0, gg.length - 1);
              console.log(gg)
              //do something
              let zz1 = that.data.zz1
              zz1.push(gg)
              that.setData({
                imag1: zz1
              })
            }
          })
        }
      }
    });
  },
  ViewImage1(e) {
    wx.previewImage({
      urls: this.data.imgList1,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg1(e) {
    wx.showModal({
      content: '确定要删除这段回忆吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          this.data.imgList1.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList1: this.data.imgList1
          })
        }
      }
    })
  },

  
  getname(e) {
    this.setData({
      name: e.detail.value
    })
  },
  shopname(e) {
    this.setData({
      shopname: e.detail.value
    })
  },
  textareaBInput(e) {
    console.log(e)
    this.setData({
      des: e.detail.value
    })
  },


  tijiao() {
    console.log(this.data.imag1)
    if (app.globalData.hasLogin == true) {
      let that = this
      if (that.data.address == '') {
        wx.showToast({
          title: '详细地址不能为空',
          icon: 'none'
        })
        return false
      }
      if (this.data.index == '') {
        wx.showToast({
          title: '商家分类不能为空',
          icon: 'none'
        })
        return false
      }
      if (this.data.name == '') {
        wx.showToast({
          title: '商家名称不能为空',
          icon: 'none'
        })
        return false
      }
      if (this.data.name == '') {
        wx.showToast({
          title: '联系人不能为空',
          icon: 'none'
        })
        return false
      }
      if (this.data.time == '') {
        wx.showToast({
          title: '营业开始时间不能为空',
          icon: 'none'
        })
        return false
      }
      if (this.data.time == '') {
        wx.showToast({
          title: '营业结束时间不能为空',
          icon: 'none'
        })
        return false
      }
      if (this.data.index1 == '') {
        wx.showToast({
          title: '入住时间不能为空',
          icon: 'none'
        })
        return false
      }
      if (this.data.imgList == []) {
        wx.showToast({
          title: '商家logo不能为空',
          icon: 'none'
        })
        return false
      }
      if (this.data.imgList1 == []) {
        wx.showToast({
          title: '商家轮播不能为空',
          icon: 'none'
        })
        return false
      }
      if (this.data.des == '') {
        wx.showToast({
          title: '商家介绍不能为空',
          icon: 'none'
        })
        return false
      }
      if (this.data.phone == '') {
        wx.showToast({
          title: '联系方式不能为空',
          icon: 'none'
        })
        return false
      }
      if (!check.isValidPhone(this.data.phone)) {
        wx.showModal({
          title: '错误信息',
          content: '手机号输入不正确',
          showCancel: false
        });
        return false;
      }
      let bb = parseInt(that.data.index1) + parseInt(1);
      util.request(api.ApplyMerchant, {
        address: that.data.address,
        classification: that.data.picker[that.data.index],
        endTime: that.data.time1,
        geometry: {
          "lat": that.data.lat,
          "lng": that.data.lng
        },
        introduction: that.data.des,
        logo: that.data.imag,
        name: that.data.shopname,
        pay: true,
        phone: that.data.phone,
        rotationImg: JSON.stringify(that.data.imag1),
        startTime: that.data.time,
        time: bb,
        touchMan: that.data.name
      }, 'post', {
        'Content-Type': 'application/json',
        'X-Qxmall-Token': wx.getStorageSync('token')
      }).then(function(res) {
        if (res.code == 200) {
          wx.showModal({
            title: '申请成功',
            content: '申请成功，请耐心等待，我们会尽联系你',
            showCancel:false,
            success: function(res) {
              if (res.cancel) {
                //点击取消,默认隐藏弹框
              } else {
                //点击确定
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        } 
        if(res.code!=200){
          wx.showModal({
            title: '错误信息',
            content: res.msg,
            showCancel: false
          })
        }
      })
    } else {
      wx.navigateTo({
        url: '../../login/login',
      })
    }
  },




  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({

      phone: wx.getStorageSync("phone")
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})